import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import {
  getCommentsByIdAction,
  getReplyCommentsByIdAction,
  sendCommentByIdAction,
} from '@/store/action/comment';
import { useAppSelector } from '@/store';
type Props = {
  // 评论的作者的名字
  name?: string;

  onBack: () => void;
};

export default function CommentInput({ name, onBack }: Props) {
  const { detail } = useAppSelector((state) => state.article);
  const { art_id } = detail;
  const { originComment } = useAppSelector((state) => state.comment);
  const { com_id } = originComment;

  const [value, setValue] = useState('');
  const dispatch = useDispatch();
  const handlePublish = async () => {
    // 根据originComment是否为空，判断现在是在回复文章。、还是回复评论
    // com_id存在，回复品论
    // 不存在，回复文章
    if (com_id) {
      await dispatch(sendCommentByIdAction({ content: value, target: com_id, art_id }));
      dispatch(getReplyCommentsByIdAction({ type: 'c', source: com_id }));
      onBack();
      Toast.show({ content: '发表成功' });
      return;
    }
    await dispatch(sendCommentByIdAction({ content: value, target: art_id }));
    dispatch(getCommentsByIdAction({ type: 'a', source: art_id }));
    onBack();
    Toast.show({ content: '发表成功' });
  };
  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="publish" onClick={handlePublish}>
            发表
          </span>
        }
        onBack={onBack}
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {/* 回复别人的评论时显示：@某某 */}
        {name && <div className="at">@{name}:</div>}

        <TextArea placeholder="说点什么~" rows={10} value={value} onChange={setValue} />
      </div>
    </div>
  );
}
